import React, { useEffect } from "react";
import { useLoaderData, useLocation, useNavigate } from "react-router";
import { useNavigateCacheRouter } from "@/hooks/modules/useRouter";
import { getCookieToken } from "@/utils/cookies";
import { useShallow } from "zustand/react/shallow";
import { useMenuStore } from "@/store/menus";

interface Props {
  children: React.ReactNode;
}

// 路由白名单
const ROUTER_WHITE_LIST: string[] = ["/404"];

const RouterGuard: React.FC<Props> = ({ children }) => {
  const { authMenuList } = useMenuStore(useShallow((state) => ({ authMenuList: state.authMenuList })));
  const { pathname } = useLocation();
  const navigate = useNavigate();
  const loader = useLoaderData();
  const token = getCookieToken();

  const { setNavigateCache } = useNavigateCacheRouter();

  // 注册全局 navigate
  setNavigateCache(navigate);

  useEffect(() => {
    loader && (document.title = loader?.title ? `${loader?.title} - ${import.meta.env.VITE_APP_TITLE}` : import.meta.env.VITE_APP_TITLE);

    // 路由白名单
    if (ROUTER_WHITE_LIST.includes(pathname)) return;

    if (token && authMenuList.length && pathname === "/login") {
      // 如果 token 和 菜单数据都存在 要访问的不是登录页的话，则重定向到首页
      navigate("/home");
    } else if ((!token && pathname !== "/login") || (!authMenuList.length && !token && pathname !== "/login")) {
      // 如果 token 不存在访问的不是登录页 或 token 和 菜单数据都不存在 访问的是非登录页，则重定向到登录页面
      navigate("/login", { replace: true });
    }
  }, [loader]);

  return children;
};

export default RouterGuard;
